package com.toro.server.handler;

import com.toro.dao.GroupSession;
import com.toro.dao.GroupSessionFactory;
import com.toro.domain.Group;
import com.toro.message.GroupJoinRequestMessage;
import com.toro.message.GroupJoinResponseMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: GroupJoinRequestMessageHandler
 * @Description:
 * @Author: ToroLHZ
 * @Date: 2023/12/11 17:48
 */
@Slf4j
@ChannelHandler.Sharable
public class GroupJoinRequestMessageHandler extends SimpleChannelInboundHandler<GroupJoinRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, GroupJoinRequestMessage groupJoinRequestMessage) throws Exception {
        log.info("加入群请求体:{}", groupJoinRequestMessage);
        String groupName = groupJoinRequestMessage.getGroupName();
        String username = groupJoinRequestMessage.getUsername();
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        boolean emptyGroup = groupSession.EmptyGroup(groupName);
        GroupJoinResponseMessage joinResponseMessage = null;
        if (emptyGroup) {
            Group group = groupSession.joinMember(groupName, username);
            if (group != null) {
                joinResponseMessage = new GroupJoinResponseMessage(true, username + "加入群" + groupName + "成功");
                channelHandlerContext.writeAndFlush(joinResponseMessage);
            } else {
                joinResponseMessage = new GroupJoinResponseMessage(false, groupName + "异常");
                channelHandlerContext.writeAndFlush(joinResponseMessage);
            }
        } else {
            joinResponseMessage = new GroupJoinResponseMessage(false, groupName + "不存在");
            channelHandlerContext.writeAndFlush(joinResponseMessage);
        }
        log.info("加入群响应体：{}", joinResponseMessage);
    }
}
